\chapter{GSI Code Structure}
\label{ch:gsi_structure}

\section{Overview of GSI Architecture}

The GSI code architecture follows a modular, three-phase design philosophy that separates initialization, execution, and finalization tasks. This design promotes maintainability, error isolation, and computational efficiency across diverse computing environments and applications.

\section{Main Process Structure}
\label{sec:main_process}

At the highest level of abstraction, the GSI system is organized around three primary phases, each implementing independent, well-defined tasks. The top-level driver routine \texttt{gsimain} (located in \texttt{gsimain.f90}) orchestrates these phases.

\subsection{Three-Phase Architecture}

The \texttt{gsimain.f90} file contains extensive metadata including:
\begin{itemize}
\item Major change history and version tracking
\item Complete input and output file specifications
\item Comprehensive subroutine and module inventory
\item External library dependencies
\item Complete exit state documentation
\item Critical namelist option discussions
\end{itemize}

The exit code documentation is particularly important for debugging, as internal GSI failures provide specific diagnostic information through these codes.

\begin{table}[htbp]
\centering
\caption{GSI Main Process Phases}
\label{tab:gsi_phases}
\begin{tabular}{|l|p{10cm}|}
\hline
\textbf{Phase} & \textbf{Main Operations} \\
\hline
\texttt{gsimain\_initialize} & 
\begin{minipage}{10cm}
\vspace{2pt}
\begin{itemize}
\item \texttt{gsi\_4dcoupler\_parallel\_init}
\item MPI initialization and processor configuration
\item Module variable default initialization
\item Namelist parameter ingestion and validation
\item 4DVAR setup (when enabled)
\item Parameter consistency verification
\item Optional single observation test setup
\item Namelist output to standard streams
\item WRF regional interface (\texttt{convert\_regional\_guess})
\item Array creation and initialization
\item Radiance and aerosol information initialization
\end{itemize}
\vspace{2pt}
\end{minipage} \\
\hline
\texttt{gsimain\_run} & 
\begin{minipage}{10cm}
\vspace{2pt}
Primary execution through \texttt{gsisub(mype)} driver routine
\vspace{2pt}
\end{minipage} \\
\hline
\texttt{gsimain\_finalize} & 
\begin{minipage}{10cm}
\vspace{2pt}
\begin{itemize}
\item Array deallocation and memory cleanup
\item MPI finalization and process termination
\item Optional 4DVAR trajectory finalization
\end{itemize}
\vspace{2pt}
\end{minipage} \\
\hline
\end{tabular}
\end{table}

\section{GSI Execution Driver: gsisub}
\label{sec:gsisub}

The \texttt{gsisub} subroutine (\texttt{gsisub.F90}) serves as the high-level driver for GSI analysis operations. Its execution flow depends on the ESMF (Earth System Modeling Framework) configuration:

\subsection{Non-ESMF Execution Path}

For standard non-ESMF operations:
\begin{enumerate}
\item \textbf{Grid Array Allocation}: Dynamic memory allocation for computational grids
\item \textbf{Metadata Extraction}: Date, grid parameters, and background file information retrieval
\item \textbf{Single Observation Testing}: Optional creation of PrepBUFR files with synthetic observations
\item \textbf{Regional Analysis Preparation}: Level 2 radar wind processing and superobservation file generation
\item \textbf{Configuration File Processing}: Initial pass reading of observation type configuration files
\item \textbf{Precipitation Model Setup}: Random number generation for forward precipitation models
\item \textbf{Core Analysis Execution}: External and internal minimization loop execution
\end{enumerate}

\subsection{Observer vs. Analysis Mode}

The execution path bifurcates based on the \texttt{lobserver} flag:

\begin{lstlisting}[language=Fortran,caption=GSI Execution Logic]
if (lobserver) then
    if initial pass: call observer_init
                    call observer_run
    if last pass: call observer_finalize
else
    call glbsoi(mype)
endif
\end{lstlisting}

When \texttt{lobserver = .true.}, GSI calculates observation departure vectors exclusively without performing analysis updates.

\section{Global Solution Interface: glbsoi}
\label{sec:glbsoi}

The \texttt{glbsoi} subroutine (\texttt{glbsoi.f90}) implements the core GSI analysis driver, orchestrating the complete variational analysis workflow:

\subsection{Initialization and Setup}
\begin{enumerate}
\item \textbf{Timer Initialization}: Performance monitoring setup
\item \textbf{Hybrid Ensemble Setup}: Configuration for ensemble-variational hybrid analysis (\texttt{l\_hyb\_ens})
\item \textbf{Alternative Minimization Check}: Validation of solver options
\item \textbf{Observer Initialization}: Observation processing system setup
\item \textbf{Temporal Validation}: GSI option compatibility with available guess time levels
\end{enumerate}

\subsection{Data Ingestion and Processing}
\begin{enumerate}
\item \textbf{Observation Reading and Distribution}: Parallel observation ingestion and processor-specific distribution
\item \textbf{Background Error Setup}: Background error covariance and balance operator initialization
\item \textbf{Ensemble Perturbation Loading}: Hybrid ensemble analysis preparation (\texttt{l\_hyb\_ens})
\item \textbf{Previous Minimization Recovery}: 4DVAR continuation from prior outer loops
\item \textbf{Predictor Error Configuration}: Background field uncertainty specification
\item \textbf{Dynamical Constraint Setup}: Physical constraint implementation
\end{enumerate}

\subsection{Main Analysis Loop}

The core analysis proceeds through outer loop iterations:

\begin{lstlisting}[language=Fortran,caption=GSI Main Analysis Loop]
do jiter=jiterstart,jiterlast
    ! Set up right hand side of analysis equation
    call setuprhsall
    
    ! Set up adjoint right hand side for forecast sensitivity
    if (forecast_sensitivity) then
        call setup_adjoint_rhs
    endif
    
    ! Inner minimization loop
    if (laltmin) then
        if (lsqrtb) call sqrtmin
        if (lbicg) call bicg
    else
        call pcinfo
        call pcgsoi  ! Primary conjugate gradient solver
    endif
    
    ! Save information for next minimization
    call save_minimization_state
    
    ! Save adjoint analysis equation output
    call save_adjoint_output
end do
\end{lstlisting}

\subsection{Analysis Finalization}
\begin{enumerate}
\item \textbf{Innovation Statistics}: Observation-minus-background (O-A) calculation and output
\item \textbf{Memory Deallocation}: Systematic array cleanup
\item \textbf{Bias Correction Updates}: Updated satellite bias correction coefficient output
\item \textbf{Observer Finalization}: Observation processing system shutdown
\item \textbf{Performance Reporting}: Timer finalization and statistics output
\end{enumerate}

\section{Observation Processing Workflow}
\label{sec:obs_processing}

\subsection{Two-Stage Observation Distribution}

GSI implements a sophisticated two-stage approach for observation processing:

\subsubsection{Stage 1: Parallel Reading into Intermediate Files}
\begin{itemize}
\item Master routine delegates to observation-type-specific readers
\item Each reader operates on dedicated processor sets
\item Native format data (e.g., BUFR) converted to intermediate \texttt{obs\_input.*} files
\item Specialized readers for numerous observation types including:
    \begin{itemize}
    \item \texttt{read\_prepbufr}: Conventional atmospheric data
    \item \texttt{read\_bufrtovs}: Satellite radiance data
    \item \texttt{read\_radar}: Radar wind and reflectivity data
    \item \texttt{read\_gps}: GPS radio occultation data
    \item \texttt{read\_ozone}: Atmospheric chemistry observations
    \end{itemize}
\end{itemize}

\subsubsection{Stage 2: Observation Scattering (obs\_para)}
\begin{itemize}
\item Each analysis processor reads all intermediate files
\item Geographic filtering selects observations within processor subdomain
\item Subdomain-specific files generated for local analysis (\texttt{pe*.obs-type\_outer-loop})
\end{itemize}

\section{Background Field Processing}
\label{sec:background_io}

\subsection{Model Interface Support}

GSI provides comprehensive support for multiple atmospheric models through dedicated interface routines:

\begin{itemize}
\item \textbf{WRF Integration}: \texttt{convert\_regional\_guess} for Weather Research and Forecasting model
\item \textbf{FV3 Support}: \texttt{convert\_fv3\_regional} for Finite Volume Cubed-Sphere model
\item \textbf{Generic Interface}: \texttt{read\_guess} for standard atmospheric model formats
\end{itemize}

\subsection{Background Field Metadata}

The \texttt{gesinfo} subroutine extracts essential metadata from background files:
\begin{itemize}
\item Temporal information (analysis time, forecast validity)
\item Grid specifications (resolution, domain boundaries, vertical levels)
\item Model-specific parameters and coordinate systems
\item Quality control flags and processing history
\end{itemize}

This metadata drives subsequent observation processing and analysis configuration, ensuring consistency between background fields and observational data.

\section{Configuration Management}

\subsection{Information File Processing}

GSI reads multiple configuration files during initialization to control observation processing and analysis behavior:

\begin{table}[htbp]
\centering
\caption{GSI Configuration Files}
\label{tab:config_files}
\begin{tabular}{|l|l|p{7cm}|}
\hline
\textbf{File} & \textbf{Reader} & \textbf{Purpose} \\
\hline
\texttt{convinfo} & \texttt{convinfo\_read} & Conventional data configuration: usage flags, time windows, quality control, thinning parameters \\
\hline
\texttt{radinfo/satinfo} & \texttt{radinfo\_read} & Satellite radiance control: channel selection, bias correction, quality control, CRTM settings \\
\hline
\texttt{ozinfo} & \texttt{ozinfo\_read} & Ozone data configuration: layer selection, observation errors, usage flags \\
\hline
\texttt{pcpinfo} & \texttt{pcpinfo\_read} & Precipitation data parameters: usage flags, error specifications \\
\hline
\texttt{coinfo} & \texttt{coinfo\_read} & Carbon monoxide data configuration \\
\hline
\texttt{aeroinfo} & \texttt{aeroinfo\_read} & Aerosol data assimilation parameters \\
\hline
\texttt{aircraftinfo} & \texttt{aircraftinfo\_read} & Aircraft temperature bias correction settings \\
\hline
\end{tabular}
\end{table}

These configuration files provide fine-grained control over observation usage, error characteristics, and quality control procedures, enabling customization for diverse meteorological applications and research requirements.